#include "../encoding.cc"
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>

const char *encoding_to_str(gitee::encoding_t e) {
  //
  constexpr struct {
    gitee::encoding_t e;
    const char *p;
    std::size_t len;
  } em[] = {{gitee::encoding_t::binary, "ASCII-8BIT", sizeof("ASCII-8BIT") - 1},
            {gitee::encoding_t::utf7, "UTF-7", sizeof("UTF-7") - 1},
            {gitee::encoding_t::utf8, "UTF-8", sizeof("UTF-8") - 1},
            {gitee::encoding_t::utf8withbom, "UTF-8 (with BOM)",
             sizeof("UTF-8 (with BOM)") - 1},
            {gitee::encoding_t::utf16le, "UTF-16LE", sizeof("UTF-16LE") - 1},
            {gitee::encoding_t::utf16be, "UTF-16BE", sizeof("UTF-16BE") - 1},
            {gitee::encoding_t::utf32le, "UTF-32LE", sizeof("UTF-32LE") - 1},
            {gitee::encoding_t::utf32be, "UTF-32BE", sizeof("UTF-32BE") - 1}};
  for (auto &x : em) {
    if (x.e == e) {
      return x.p;
    }
  }
  return "Empty";
}

int main(int argc, char const *argv[]) {
  if (argc < 2) {
    fprintf(stderr, "usage: %s file\n", argv[0]);
    return 1;
  }
  auto file = fopen(argv[1], "rb");
  if (file == nullptr) {
    fprintf(stderr, "unable open %s\n", argv[1]);
    return 1;
  }
  char buf[4096];
  auto n = fread(buf, 1, 4096, file);
  fclose(file);
  auto e =
      gitee::DetectBufferEncoding(reinterpret_cast<unsigned char *>(buf), n);
  fprintf(stderr, "File: %s Encoding: %s\n", argv[1], encoding_to_str(e));
  return 0;
}
